5200 Final Project Line Chart

library(tidyverse)
# Load the data
stadium <- read_csv("Nationals_Stadium_Stats.csv")
# https://www.baseball-reference.com/teams/WSN/attend.shtml
# Drop year 2020 due to the Covid impact
stadium <- stadium %>% filter (Year!=2020 & Year!=2024)

# Convert 'Est. Payroll' to numeric after removing commas and dollar signs
stadium$`Est. Payroll` <- as.numeric(gsub("[,$]", "", stadium$`Est. Payroll`))
library(plotly)
# Create a base plot
p <- plot_ly(stadium, x = ~Year, y = ~Attendance, type = 'scatter', mode = 'lines+markers', name = 'Attendance')

# Add other traces
p <- p %>% add_trace(y = ~`Est. Payroll`, name = "Estimated Payroll", visible = F)
p <- p %>% add_trace(y = ~`Attend/G`, name = "Attendance per Game", visible = F)
p <- p %>% add_trace(y = ~PPF, name = "Pitcher's Park Factor", visible = F)
p <- p %>% add_trace(y = ~BPF, name = "Batter's Park Factor", visible = F)

# Define layout and buttons for interactivity
final_plot <- p %>% layout(
  title = 'Interactive Visualization of Washington Nationals Statistics',
  xaxis = list(title = 'Year'),
  yaxis = list(title = 'Value'),
  updatemenus = list(
    list(
      type = 'buttons',
      direction = 'left',
      x = 0,
      xanchor = 'left',
      y = -0.2,
      yanchor = 'top',
      buttons = list(
        list(method = 'update', args = list(list(visible = c(T, F, F, F, F)), list(title = 'Attendance')), label = 'Attendance'),
        list(method = 'update', args = list(list(visible = c(F, T, F, F, F)), list(title = 'Estimated Payroll')), label = 'Estimated Payroll'),
        list(method = 'update', args = list(list(visible = c(F, F, T, F, F)), list(title = 'Attendance per Game')), label = 'Attendance per Game'),
        list(method = 'update', args = list(list(visible = c(F, F, F, T, F)), list(title = 'Pitcher\'s Park Factor')), label = 'Pitcher\'s Park Factor'),
        list(method = 'update', args = list(list(visible = c(F, F, F, F, T)), list(title = 'Batter\'s Park Factor')), label = 'Batter\'s Park Factor')
      )
    )
  )
)

# Show the plot
final_plot